/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root)
    {
        vector<int> arr;
        if (!root)
            return arr;
        stack<TreeNode*> st;

        TreeNode* p = root;
        TreeNode* tmp = NULL;

        while (p || !st.empty())
        {
            while (p)
            {
                st.push(p);
                p = p->left;
            }
            p = st.top();
            while (p->right == NULL || p->right == tmp)
            {
                arr.push_back(p->val);
                st.pop();
                if (st.empty())
                {
                    p = NULL;
                    break;
                }
                tmp = p;
                p = st.top();

            }

            if (p)
                p = p->right;
        }
        return arr;
    }
};